<template>
    <!-- 地图 -->
    <div class="map-content" id="map-content"></div>

</template>
<script setup>
import { computed, onMounted, onUnmounted, ref } from "vue";
// 导入axios
import axios from "axios";
// 导入高德地图
import AMapLoader from "@amap/amap-jsapi-loader";


// 配置内容
const AMapKey = ""; // 高德平台web应用key
const AMapSecurityJsCode = ""; // 高德平台申请key时的安全密钥
const QWeatherApiKey = ""; // 和风天气平台应用的API Key
const QWeatherUrl = `https://devapi.qweather.com/v7/weather`; // 和风天气请求数据url前缀


// 高德地图必须配合安全密钥使用
window._AMapSecurityConfig = {
  securityJsCode: AMapSecurityJsCode,//申请key时的安全密钥
};


// 地图实例对象
let map = null;
// 地图地理编码对象
const MapGeocoder = ref(null);
// 弹窗信息
const infoWindow = ref(null);
onMounted(() => {
    AMapLoader.load({
        key: AMapKey, // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.Geocoder","AMap.DistrictSearch","AMap.InfoWindow"], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
    }).then((AMap) => {

        // 地图初始化
        map = new AMap.Map("map-content", {
            // 设置地图容器id
            viewMode: "2D", // 是否为3D地图模式
            zoom: 5, // 初始化地图级别
            zooms: [5,5], // 地图级别限制
            center: [116.397428, 39.90923], // 初始化地图中心点位置
        });

        // 地址编码
        MapGeocoder.value = new AMap.Geocoder({
            city: "全国", //城市设为北京，默认：“全国”
            radius: 1000, //范围，默认：500
            exports:"all"
        });

        // 信息弹窗实例对象
        infoWindow.value = new AMap.InfoWindow({
            offset: new AMap.Pixel(0, -30)
        });

        // 创建districtSearch实例
        const district = new AMap.DistrictSearch({
            level: 'city', // 查询级别为市级
            subdistrict: 1, // 0:不返回下级行政区,1:返回一级行省
        });

        // 缓存省份信息
        let provinceData = JSON.parse(localStorage.getItem("China_Province"));
        if (provinceData) {
            for (let i = 0; i < provinceData.length; i++) {
                const districtInfo = provinceData[i];
                // 经纬度
                const center = districtInfo.center;
                // 省会名称
                const name = districtInfo.name;
                // 在地图上添加省会标记
                let marker = new AMap.Marker({
                    map,
                    position: center,
                    title: name,
                });
                marker.on('click', showInfoClick);
                // marker.emit('click', {target: marker});
            }
            map.setFitView(); // 视野自适应
        } else { 
            // 行政区查询
            district.search('中国', (status, result) => {
                // 清除原有的图层
                map.clearMap();
                // console.log(result)
                if (status === 'complete') {
                    if (result.districtList && result.districtList.length) {
                        const districts = result.districtList[0].districtList;
                        localStorage.setItem("China_Province", JSON.stringify(districts));
                        for (let i = 0; i < districts.length; i++) {
                        const districtInfo = districts[i];
                        // 经纬度
                        const center = districtInfo.center;
                        // 省会名称
                        const name = districtInfo.name;
                        // 在地图上添加省会标记
                        new AMap.Marker({
                            map,
                            position: center,
                            title: name,
                        });
                        }
                        map.setFitView(); // 视野自适应
                    }
                }
            });
        }

        // 地图点击事件
        // map.on('click', showInfoClick);

        // 视野自适应
        map.setFitView();
    })
    .catch((e) => {
      console.log(e);
    });
});


// 天气信息
const weatherShow = ref([]);
// 计算显示天气信息
const weatherInner = computed(() => {
    let weatherStr = "";
    weatherShow.value.forEach((item) => { 
        weatherStr +=`
            <div class="weather-day" style="width: 20rem;display: flex;align-items: center;justify-content: space-between;margin-bottom: 9px;">
                <span style="font-size: 1rem;">${item.fxDate}</span>
                <span style="font-size: 1rem;">${item.textDay}-${item.textNight}</span>
                <span style="font-size: 1rem;">${item.tempMax}~${item.tempMin}℃</span>
            </div>`
    })
    return weatherStr
});


// 地图点击事件
const showInfoClick = async (e) => { 
    // console.log(e)
    let { lng, lat } = e.lnglat;
    let resData = await getWeather(`${lng},${lat}`);
    // console.log(resData);
    weatherShow.value = [];
    weatherShow.value = [...resData];

    // 设置弹窗信息内容
    infoWindow.value.setContent(` <div class="weather-box">
        <div class="waether-content">
            <h4 class="weather-title">天气预报</h4>
        ${weatherInner.value}
        </div>
    </div>`);

    // 打开信息弹窗
    infoWindow.value.open(map, e.target.getPosition());

    // 地理编码逆解析
    // MapGeocoder.value.getAddress([lng,lat], function(status, result) {
    //   console.log(status, result);
    // //   if (status === 'complete' && result.regeocode) {
    // //   }
    // });

}

// 根据城市坐标获取天气数据
const getWeather = (city) => {
    const url = `${QWeatherUrl}/7d?location=${city}&key=${QWeatherApiKey}`;
    return new Promise((resolve,reject) => { 
        axios.get(url).then(response => {
            // console.log(response)
            if (response.data.code === "200") {
                let weatherOriginal = response.data.daily;
                // 定义需要保留的属性
                const keepAttributes = ["fxDate","textDay","textNight","tempMax","tempMin"];
                // 过滤对象数组，去除不需要的属性
                const filterData = weatherOriginal.map(item =>
                    keepAttributes.reduce((obj, key) => {
                        obj[key] = item[key];
                        return obj;
                    }, {})
                );
                // console.log(filterData);
                resolve(filterData);
          } else {
                console.error("查询天气失败:", response.data.code);
                resolve(response.data.code);
          }
        })
        .catch(error => {
            console.error("请求失败:", error);
            reject(error)
        });
    })
}

onUnmounted(() => {
  map?.destroy();
});

</script>

<style scoped>
    #map-content {
        width: 100%;
        height: 100vh;
    }
</style>


